<template>
    <n-button v-bind="mergedProps" v-if="visible()" @click="handleClick">
        <template v-if="title && !$slots['default']">{{ title }}</template>
        <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
            <slot :name="item" v-bind="data || {}"> </slot>
        </template>
    </n-button>
</template>

<script setup lang="ts">
import type { ButtonProps, IconProps } from "./types"
import { hasPermission, isVisible } from "@/components/hooks"
import { isObject, isString, renderIcon } from "@/utils"

const props = withDefaults(defineProps<ButtonProps>(), {
    type: "default",
    size: "medium",
    block: false,
    htmlType: "button",
    bordered: true,
    visible: true,
    disabled: false
})

const convertProps = computed(() => {
    const result: Recordable = {
        type: props.type,
        size: props.size,
        block: props.block
    }
    if (props.shape === "circle") {
        result.circle = true
    } else if (props.shape === "round") {
        result.round = true
    } else if (props.shape === "text") {
        result.text = true
    }
    if (props.bordered === false) {
        result.bordered = false
    } else if (props.bordered === "dashed") {
        result.dashed = true
    }
    if (isString(props.icon)) {
        result.renderIcon = renderIcon(props.icon as string)
    } else if (isObject(props.icon)) {
        result.renderIcon = renderIcon((props.icon as IconProps).icon, props.icon)
    }
    if (result.renderIcon) {
        props.iconPlacement && (result.iconPlacement = props.iconPlacement)
    }
    props.color && (result.color = props.color)
    props.textColor && (result.textColor = props.textColor)
    props.tag && (result.tag = props.tag)
    props.htmlType && (result.attrType = props.htmlType)
    return result
})

const attrs = useAttrs()

const emits = defineEmits(["click"])

const mergedProps = computed(() => ({
    ...attrs,
    ...unref(convertProps)
}))

function handleClick(e: MouseEvent) {
    e.preventDefault()
    emits("click", props.data)
}

function visible() {
    return hasPermission(props) && isVisible(props, props.data)
}
</script>
